/**
 * Copyright(C) 2012 Luvina
 * LoginNameValidator.java, 26-05-2012 NguyenVietDung
 */
package net.luvina.manageuser.validator;

import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import net.luvina.manageuser.util.Message;

/**
 * LoginNameValidator: Custome validate của JSF Thực hiện validate dữ liệu nhập
 * vào cho hạng mục tên đăng nhập
 *
 * @author NguyenVietDung
 */
public class LoginNameValidator implements Validator {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component, Object str) throws ValidatorException {
		FacesMessage message = new FacesMessage();
		String loginNameStr = String.valueOf(str);
		String firstLoginNamePattern = "^[A-Za-z_]{1}[A-Za-z0-9_]*$";
		String secondLoginNamePattern = "^[A-Za-z_]{1}[A-Za-z0-9_]{3,15}$";
		String labelField = (String) component.getAttributes().get("label");

		boolean isMatchFirst = Pattern.matches(firstLoginNamePattern, loginNameStr);
		boolean isMatchSecond = Pattern.matches(secondLoginNamePattern, loginNameStr);
		if (!isMatchFirst) {
			message.setSummary(Message.getString("ER019"));
			message.setDetail(Message.getString("ER019"));
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
		if (!isMatchSecond) {
			StringBuilder msgStrBuilder = new StringBuilder();
			msgStrBuilder.append(" 「").append(labelField).append("」 ").append(Message.getString("ER007_loginName"));
			message.setSummary(msgStrBuilder.toString());
			message.setDetail(msgStrBuilder.toString());
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}

	}

}
